package com.toocms.jinjuhang.ui.mine.order.evaluate

import android.app.Application
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.RelativeSizeSpan
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.databinding.ObservableFloat
import com.blankj.utilcode.util.StringUtils
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.order_info.DoCommentData
import com.toocms.jinjuhang.data.order_info.OrderCommodityItemData
import com.toocms.jinjuhang.data.system.UploadData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger

class OrderEvaluateModel(application: Application, bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {

    val dataObservableField by lazy {
        val content = bundle?.getParcelable(Constants.BundleKey.KEY_ORDER_COMMODITY)
            ?: OrderCommodityItemData()
        ObservableField(content)
    }
    val starObservableField = ObservableFloat(5f)
    val contentObservableField = ObservableField<String>()
    val imageItems = ObservableArrayList<OrderEvaluateImageItemModel>()
    val imageImageBinding = ItemBinding.of<OrderEvaluateImageItemModel>(
        BR.orderEvaluateImageItemModel, R.layout.item_order_evaluate_upload_image
    )
    val confirmClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val orderId = dataObservableField.get()?.order_id ?: return@BindingAction
        val orderGoodsId = dataObservableField.get()?.order_goods_id ?: return@BindingAction
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_id"] = orderId
        params["order_goods_id"] = orderGoodsId
        params["level"] = starObservableField.get().toString()
        params["content"] = contentObservableField.get()
        params["pictures"] = selectedImageIds()
        requestData(Urls.OrderInfo.DO_COMMENT,
            params,
            resultClass = DoCommentData::class.java,
            result = {
                Messenger.getDefault().sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_ORDER)
                val bundle = Bundle()
                bundle.putString(Constants.BundleKey.KEY_POINTS, it.points)
                startFragment(OrderEvaluateResultFgt::class.java, bundle, true)
            })
    })

    init {
        imageItems += OrderEvaluateImageItemModel(this)
    }

    fun selectImage() {
        val maxSelectImageNumber = if (!imageItems.isNullOrEmpty() && TextUtils.isEmpty(
                imageItems[0].item.get()?.id ?: ""
            )
        ) {
            Constants.Extra.EVALUATE_UPLOAD_IMAGE_MAX_NUMBER - imageItems.size + 1
        } else {
            Constants.Extra.EVALUATE_UPLOAD_IMAGE_MAX_NUMBER - imageItems.size
        }
        startSelectMultipleImageAty(null,
            maxSelectImageNumber,
            object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    val imagePaths = mutableMapOf<String, String?>()
                    result?.forEachIndexed { index, media ->
                        imagePaths["image$index"] = media.realPath
                    }
                    requestData(Urls.System.UPLOAD,
                        filePaths = imagePaths,
                        resultClass = UploadData::class.java,
                        result = {
                            it.list?.forEach {
                                imageItems += OrderEvaluateImageItemModel(
                                    this@OrderEvaluateModel, ObservableField(it)
                                )
                            }
                            if (Constants.Extra.EVALUATE_UPLOAD_IMAGE_MAX_NUMBER < imageItems.size && TextUtils.isEmpty(
                                    imageItems[0].item.get()?.id
                                )
                            ) {
                                imageItems.remove(imageItems[0])
                            }
                        })
                }

                override fun onCancel() {

                }
            })
    }


    fun price(commodityType: String?, sum: String?) = when (commodityType) {
        Constants.Extra.COMMODITY_TYPE_INTEGRAL -> {
            val sum = if (sum.isNullOrEmpty()) "00" else sum
            SpannableStringBuilder("$sum${StringUtils.getString(R.string.str_integral)}").apply {
                setSpan(
                    RelativeSizeSpan(0.8f), sum.length, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }

        else -> {
            val sum = if (sum.isNullOrEmpty()) "0.00" else sum
            "${StringUtils.getString(R.string.str_money_symbol)}$sum"
        }
    }

    private fun selectedImageIds(): String {
        val result = StringBuilder()
        imageItems.forEach {
            val imageId = it.item.get()?.id ?: return@forEach
            if (result.isNotEmpty()) result.append(Constants.Extra.DECOLLATOR_DEFAULT)
            result.append(imageId)
        }
        return result.toString()
    }

}
